using System.Collections.Generic;
using System.IO;
using Pandora;
using UnityEditor;
using UnityEngine;

namespace NeatlyEditor.UI
{
    public class SameTrim
    {
        public static void AddSameTrim(Object obj)
        {
            string rootPath = AssetDatabase.GetAssetPath(obj);
            var list = PdrFileUtil.GetFilesName(rootPath, ".png");
            List<Texture2D> texList = new List<Texture2D>();
            int maxWidth = 0;
            int maxHeight = 0;
            for (int i = 0; i < list.Count; i++)
            {
                var importer = AssetImporter.GetAtPath(list[i]) as TextureImporter;
                importer.isReadable = true;
                importer.npotScale = TextureImporterNPOTScale.None;
                importer.SaveAndReimport();
            }

            for (int i = 0; i < list.Count; i++)
            {
                Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(list[i]);
                if (tex.width > maxWidth)
                {
                    maxWidth = tex.width;
                }

                if (tex.height > maxHeight)
                {
                    maxHeight = tex.height;
                }

                texList.Add(tex);
            }

            AssetDatabase.Refresh();

            for (int i = 0; i < texList.Count; i++)
            {
                var curTex = texList[i];
                Texture2D newTex = new Texture2D(maxWidth, maxHeight, TextureFormat.RGBA32, false);
                if (maxWidth == curTex.width && maxHeight == curTex.height)
                {
                    continue;
                }

                int left = (maxWidth - curTex.width) / 2;
                int top = (maxHeight - curTex.height) / 2;
                int w = curTex.width + left;
                int h = curTex.height + top;
                for (int j = 0; j < newTex.width; j++)
                {
                    for (int k = 0; k < newTex.height; k++)
                    {
                        if (j < left || k < top)
                        {
                            newTex.SetPixel(j, k, new Color(0, 0, 0, 0));
                        }
                        else if (j >= w || k >= h)
                        {
                            newTex.SetPixel(j, k, new Color(0, 0, 0, 0));
                        }
                        else
                        {
                            var color = curTex.GetPixel(j - left, k - top);
                            newTex.SetPixel(j, k, color);
                        }
                    }
                }

                var bytes = newTex.EncodeToPNG();
                File.WriteAllBytes(list[i], bytes);
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }
}